# -*- coding: utf-8 -*-
import os
import re
import subprocess
from subprocess import Popen

__name__ = "cas-lib"
_LOG = False


def recursion_dir(dir: str, filename_pattern='.*', dirname_pattern='.*') -> 'list[str]':
    '''
    Get all files in `dir` whose name matches `pattern`
    '''
    files = []
    for fn in os.listdir(dir):
        p = os.path.join(dir, fn)
        if os.path.isdir(p):
            if _LOG:
                print('[dir]', p)
            files.extend(recursion_dir(p, filename_pattern, dirname_pattern))
        elif os.path.isfile(p):
            if re.match(dirname_pattern, dir) and re.match(filename_pattern, fn):
                if _LOG:
                    print('[file]', p)
                files.append(p)
        pass
    return files


def cas_exec(script: str, args: str, pipeout=False):
    '''
    Blocking exec
    '''

    try:
        if pipeout:
            dn = os.path.dirname(pipeout)
            if not os.path.isdir(dn):
                if _LOG:
                    print('mkdir -p', dn)
                os.makedirs(dn)
            out_pipe = open(pipeout, 'w')
        else:
            out_pipe = subprocess.STDOUT

        if not os.path.isfile('./cas'):
            print('./cas not found')
            return

        print('./cas exec', script, args)
        proc = Popen(
            ['./cas', 'exec', script, args], shell=False, universal_newlines=True,
            stdin=subprocess.DEVNULL, stdout=out_pipe, stderr=subprocess.STDOUT
        )  # 2>&1

        output, _ = proc.communicate(timeout=3600)
    except subprocess.TimeoutExpired:
        print('<timeout>', proc.pid, script, args)
        proc.kill()
        output, _ = proc.communicate()

    if not pipeout:
        print('<output>', script, args)
        print(output)
    return
